//
//  Request.m
//  iFlower
//
//  Created by thohd on 7/23/10.
//  Copyright 2010 iNIL.me. All rights reserved.
//

#import "JSON.h"
#import "Request.h"
#import "User.h"
#import "Order.h"
#import "Address.h"

NSString * const kBaseURL = @"http://www.flowersonline24.com/iphoneApp/home.php?";
NSString * const kiPhoneRoot = @"http://www.flowersonline24.com/iphoneApp/%@";
NSString * const kLoginPage = @"login.php";
NSString * const kSaveOrder = @"home.php?key=saveOrder";
NSString * const kCountryList = @"key=countryList";
NSString * const kCategoryPattern = @"cat=%d";
NSString * const kProductInfoPattern = @"productid=%@";
NSString * const kGetAddressBookPattern = @"login=%@&key=getAddressBook";
NSString * const kAddAddressBookPattern = @"home.php?login=%@&key=addAddressBook";
NSString * const kRegisterUserPattern = @"home.php?key=register";
NSString * const kCategoryList = @"http://www.flowersonline24.com/api/category.php";
@implementation Request

@synthesize entries = entries_;

static Request *sharedCLDelegate = nil;

+ (Request *)sharedRequest {
    @synchronized(self) {
        if (sharedCLDelegate == nil) {
            sharedCLDelegate = [Request new]; // assignment not done here
        }
    }
    return sharedCLDelegate;
}

#pragma mark -

- (id) init
{
	if ((self = [super init]) != nil) {
		entries_ = [NSMutableArray new];
		json_ = [NSMutableData new];
	}
	return self;
}

- (void) dealloc
{
	[connection_ release];
	[entries_ release];
	[json_ release];
	[super dealloc];
}

- (void)startConnectionWithURL:(NSURL*)url
{
	if (connection_ == nil)
	{
		NSURLRequest* request = [NSURLRequest requestWithURL: url
												 cachePolicy: NSURLRequestReloadIgnoringLocalCacheData timeoutInterval: 30.0];
		connection_ = [[NSURLConnection connectionWithRequest: request delegate: self] retain];
		NSLog(@"Request with url:%@",url);
	}	
}
- (void)post:(NSString*)pageURL withBody:(NSString*)dataBody
{
	if (connection_==nil) {
		NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
		NSLog(@"post to: %@",[NSString stringWithFormat:kiPhoneRoot,pageURL]);
		[request setURL:[NSURL URLWithString:[NSString stringWithFormat:kiPhoneRoot,pageURL]]];
		[request setHTTPMethod:@"POST"];
		//set headers
		NSString *contentType = [NSString stringWithFormat:@"application/x-www-form-urlencoded"];
		[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
		NSLog(@"body:%@",dataBody);
		[request setHTTPBody:[dataBody dataUsingEncoding:NSUTF8StringEncoding]];
		connection_ = [[NSURLConnection connectionWithRequest:request delegate:self] retain];		
	}
	
}
#pragma mark -
#pragma mark NSURLConnection

- (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error
{
	[[NSNotificationCenter defaultCenter] postNotificationName: @"ContentFailed" object: nil];

	[connection_ release];
	connection_ = nil;
}

- (void) connectionDidFinishLoading: (NSURLConnection*) connection
{
	// Parse the JSON and store it into the Catalog
	
	NSString* json = [[[NSString alloc] initWithData: json_ encoding: NSUTF8StringEncoding] autorelease];
	//NSLog(@"JSON:%@",json);
	NSArray* entries = [json JSONValue];
	
	[entries_ removeAllObjects];
	
	for (NSDictionary* dictionary in entries)
	{
		[entries_ addObject: dictionary];
	}
	
	// Sort the books by title
	
//	[entries_ sortUsingFunction: SortCatalogEntriesByTitle context: nil];
	
	// Let others know that the catalog reloaded
	
	[[NSNotificationCenter defaultCenter] postNotificationName: @"ContentLoaded" object: nil];
	
	// Release everything
	
	[connection_ release];
	connection_ = nil;
}

- (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response
{
	[json_ setLength: 0];
}

- (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data
{
    [json_ appendData: data];
}

#pragma mark -
#pragma mark Public methods

- (void) getCategoryList
{
	[self startConnectionWithURL:[NSURL URLWithString:[kCategoryList stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]]];
}

- (void) getFlowerByCategory: (NSInteger)catId 
{
	[self startConnectionWithURL:[NSURL URLWithString:[[kBaseURL stringByAppendingFormat:kCategoryPattern,catId] stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]]];
}
- (void) listCountry
{
	[self startConnectionWithURL:[NSURL URLWithString:[[kBaseURL stringByAppendingString:kCountryList] stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]]];
}

- (void) getCountryList
{
	[self getFlowerByCategory:281];
}

- (void) getProductInfo:(NSString*)productId
{
	[self startConnectionWithURL:[NSURL URLWithString:[[kBaseURL stringByAppendingFormat:kProductInfoPattern,productId] stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]]];
}

- (void)login:(User *)user
{
	[self post:kLoginPage withBody:[user loginData]];
}
- (void) logout
{
	[self post:kLoginPage withBody:@"mode=logout"];
}
- (void) getAddressBooks:(User*)user
{
	[self startConnectionWithURL:[NSURL URLWithString:[[kBaseURL stringByAppendingFormat:kGetAddressBookPattern,user.username] stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]]];
}
- (void) saveOrder:(Order*)order
{
	[self post:kSaveOrder withBody:[order orderData]];
}
- (void) addAddress:(Address*) address user:(User*)user
{
	[self post:[NSString stringWithFormat:kAddAddressBookPattern, user.username] withBody:[address addressData]];
}
- (void) registerUser:(User*)user
{
	[self post:kRegisterUserPattern withBody:[user registerData]];
}
@end
